import Vue from 'vue'

Vue.filter('floatToPercent', function (value, hasPercent) {
  if (typeof value === 'number') {
    value = value.toString()
  }

  if (value && value.indexOf('%') < 0) {
    let m = 0
    try {
      m += value.split('.')[1].length
    } catch (error) {
      m = 0
    }

    return ((Number(value.replace('.', '')) * 100) / Math.pow(10, m) + (hasPercent ? '%' : ''))
  }

  return value
})

Vue.filter('percentToFloat', function (value) {
  if (typeof value === 'number') {
    value = value.toString()
  }

  if (value) {
    return Number(value.replace(/%/, '')) / 100
  }

  return value
})

Vue.filter('dateObjToTime', function (value) {
  if (value) {
    let jsonDate = new Date(value).toJSON()
    return new Date(new Date(jsonDate) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
  }
  return value
})

Vue.filter('rebateAmount', function (val) {
  if (!val) {
    return ''
  }
  if (!val.cpaRatio && !val.cpsRatio) {
    return ''
  }
  if (!val.negotiable) {
    if (!parseInt(val.cpaRatio)) {
      return `[${val.cpsAmount}]`
    }
    if (!parseInt(val.cpsRatio)) {
      return `[${val.cpaRatio}]`
    }
    return `[${val.cpaRatio}+${val.cpsAmount}]`
  }
  if (!parseInt(val.cpaRatio)) {
    return `[成交金额*${val.cpsRatio}%]`
  }
  if (!parseInt(val.cpsRatio)) {
    return `[${val.cpaRatio}]`
  }
  return `[${val.cpaRatio}+成交金额*${val.cpsRatio}%]`
})
